// pages/i/address.js
const auth = require('../../utils/auth.js');
const AddressService = require('../../services/address.js');
import { areaList } from '@vant/area-data';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用户信息
    userInfo: null,
    isLoggedIn: false,
    
    // 地址列表
    addressList: [],
    loading: false,
    loadingMore: false,
    hasMore: true,
    currentPage: 1,
    pageSize: 10,
    
    // 地址表单
    showAddressForm: false,
    editingAddress: null,
    addressForm: {
      name: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detail: '',
      region: '',
      isDefault: false
    },
    
    // 地区选择器
    showRegion: false,
    areaList,
    
    // 删除确认
    showDeleteDialog: false,
    deletingAddress: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkUserAuth();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // this.data.areaList = areaList;
    // console.log(this.data.areaList);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.isLoggedIn) {
      this.loadAddressList(true);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 检查用户授权状态
   */
  async checkUserAuth() {
    try {
      const loginStatus = await auth.checkLoginStatus();
      
      if (!loginStatus.isLoggedIn) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      const userInfo = auth.getUserInfo();
      if (!auth.isValidUserInfo(userInfo)) {
        wx.showToast({
          title: '请先绑定手机号',
          icon: 'none'
        });
        return;
      }
      
      this.setData({
        isLoggedIn: true,
        userInfo: userInfo
      });
      
      // 加载地址列表
      this.loadAddressList(true);
      
    } catch (error) {
      console.error('检查用户授权失败:', error);
      wx.showToast({
        title: '授权检查失败',
        icon: 'none'
      });
    }
  },

  /**
   * 加载地址列表
   */
  async loadAddressList(refresh = false) {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: true });
      
      const page = refresh ? 1 : this.data.currentPage;
      const result = await AddressService.getAddressList({
        page: page,
        pageSize: this.data.pageSize,
        showLoading: refresh
      });
      
      if (result.success && result.data) {
        const { list, total, current_page, last_page } = result.data;
        
        this.setData({
          addressList: refresh ? list : [...this.data.addressList, ...list],
          currentPage: current_page,
          hasMore: current_page < last_page,
          loading: false
        });
      } else {
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
      
    } catch (error) {
      console.error('加载地址列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  /**
   * 加载更多地址
   */
  async loadMore() {
    if (this.data.loadingMore || !this.data.hasMore) return;
    
    try {
      this.setData({ loadingMore: true });
      
      const nextPage = this.data.currentPage + 1;
      const result = await AddressService.getAddressList({
        page: nextPage,
        pageSize: this.data.pageSize
      });
      
      if (result.success && result.data) {
        
        this.setData({
          addressList: [...this.data.addressList, ...result.data.list],
          currentPage: result.data.current_page,
          hasMore: result.data.current_page < result.data.last_page,
          loadingMore: false
        });

        
      } else {
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
        this.setData({ loadingMore: false });
      }
      
    } catch (error) {
      console.error('加载更多地址失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loadingMore: false });
    }
  },

  /**
   * 添加地址
   */
  addAddress() {
    this.resetAddressForm();
    this.setData({
      showAddressForm: true,
      editingAddress: null
    });
  },

  /**
   * 编辑地址
   */
  editAddress(e) {
    const address = e.currentTarget.dataset.address;
    this.setData({
      addressForm: {
        name: address.name,
        phone: address.phone,
        province: address.province,
        city: address.city,
        district: address.district,
        detail: address.detail,
        region: `${address.province} ${address.city} ${address.district}`,
        isDefault: address.is_default == 1
      },
      showAddressForm: true,
      editingAddress: address
    });
  },

  /**
   * 删除地址
   */
  deleteAddress(e) {
    const address = e.currentTarget.dataset.address;
    this.setData({
      showDeleteDialog: true,
      deletingAddress: address
    });
  },

  /**
   * 确认删除地址
   */
  async confirmDelete() {
    const address = this.data.deletingAddress;
    if (!address) return;
    
    try {
      const result = await AddressService.deleteAddress({
        id: address.id,
        showLoading: true
      });
      
      if (result.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 重新加载地址列表
        this.loadAddressList(true);
      } else {
        wx.showToast({
          title: result.message || '删除失败',
          icon: 'none'
        });
      }
      
    } catch (error) {
      console.error('删除地址失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        showDeleteDialog: false,
        deletingAddress: null
      });
    }
  },

  /**
   * 设置默认地址
   */
  async setDefaultAddress(e) {
    const address = e.currentTarget.dataset.address;
    
    try {
      const result = await AddressService.setDefaultAddress({
        id: address.id,
        showLoading: true
      });
      console.log('setDefaultAddress', result);
      if (result.success) {
        wx.showToast({
          title: '设置成功',
          icon: 'success'
        });

        
        
        // 重新加载地址列表
        this.loadAddressList(true);
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
      
    } catch (error) {
      console.error('设置默认地址失败:', error);
      wx.showToast({
        title: '设置失败',
        icon: 'none'
      });
    }
  },

  /**
   * 表单字段变化
   */
  onFieldChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail;
    this.setData({
      [`addressForm.${field}`]: value
    });
  },

  /**
   * 默认地址开关变化
   */
  onDefaultChange(e) {
    this.setData({
      'addressForm.isDefault': e.detail
    });
  },

  /**
   * 显示地区选择器
   */
  showRegionPicker() {
    this.setData({ showRegion: true });
  },

  /**
   * 关闭地区选择器
   */
  closeRegionPicker() {
    this.setData({ showRegion: false });
  },

  /**
   * 地区选择确认
   */
  onRegionConfirm(e) {
    const { values } = e.detail;
    const region = values.map(item => item.name).join(' ');
    
    this.setData({
      'addressForm.province': values[0].name,
      'addressForm.city': values[1].name,
      'addressForm.district': values[2].name,
      'addressForm.region': region,
      showRegion: false
    });
  },

  /**
   * 保存地址
   */
  async saveAddress() {
    const { addressForm, editingAddress } = this.data;
    
    // 表单验证
    if (addressForm.name === '') {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      });
      return;
    }
    
    if (addressForm.phone === '') {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!addressForm.province || !addressForm.city || !addressForm.district) {
      wx.showToast({
        title: '请选择所在地区',
        icon: 'none'
      });
      return;
    }
    
    if (addressForm.detail === '') {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      });
      return;
    }
    
    try {
      let result;
      
      if (editingAddress) {
        // 编辑地址
        result = await AddressService.updateAddress({
          id: editingAddress.id,
          name: addressForm.name,
          phone: addressForm.phone,
          province: addressForm.province,
          city: addressForm.city,
          district: addressForm.district,
          detail: addressForm.detail,
          isDefault: addressForm.isDefault,
          showLoading: true
        });
      } else {
        // 添加地址
        result = await AddressService.addAddress({
          name: addressForm.name,
          phone: addressForm.phone,
          province: addressForm.province,
          city: addressForm.city,
          district: addressForm.district,
          detail: addressForm.detail,
          isDefault: addressForm.isDefault,
          showLoading: true
        });
      }
      
      if (result.success) {
        wx.showToast({
          title: editingAddress ? '更新成功' : '添加成功',
          icon: 'success'
        });

        this.closeAddressForm();
        this.loadAddressList(true);
      } else {
        wx.showToast({
          title: result.message || '操作失败',
          icon: 'none'
        });
      }
      
    } catch (error) {
      console.error('保存地址失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 关闭地址表单
   */
  closeAddressForm() {
    console.log('closeAddressForm');
    this.setData({
      showAddressForm: false,
      editingAddress: null
    });
    this.resetAddressForm();
  },

  /**
   * 关闭删除确认弹窗
   */
  closeDeleteDialog() {
    this.setData({
      showDeleteDialog: false,
      deletingAddress: null
    });
  },

  /**
   * 重置地址表单
   */
  resetAddressForm() {
    this.setData({
      addressForm: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        region: '',
        isDefault: false
      }
    });
  },

  /**
   * 选择地址（用于订单页面选择）
   */
  selectAddress(e) {
    const address = e.currentTarget.dataset.address;
    
    // 如果是从其他页面跳转过来选择地址的，则返回
    const pages = getCurrentPages();
    if (pages.length > 1) {
      const prevPage = pages[pages.length - 2];
      if (prevPage.route.includes('order') || prevPage.route.includes('confirm')) {
        // 返回上一页并传递选中的地址
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('selectAddress', address);
        wx.navigateBack();
        return;
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadAddressList(true).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMore();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})